/**
 * Free software.
 */

package org.nanhill.moo.domain.search.favor;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Expression;
import org.hibernate.criterion.Order;
import org.nanhill.commons.pattern.search.SearchConstant;
import org.nanhill.commons.pattern.search.SearchException;
import org.nanhill.moo.domain.Favor;
import org.nanhill.support.hibernate.search.CriteriaSearchVisitor;

/**
 * @author alin [xalinx at gmail dot com]
 * @date 2006-11-6
 */
public class HibernateFavorListVisitor extends CriteriaSearchVisitor implements
		FavorVisitor {
	private List<Favor> favorList;

	/**
	 * @param session
	 * @param clz
	 */
	public <E extends Favor> HibernateFavorListVisitor(Class<E> clz, int start,
			int size) {
		super(clz, start, size);
	}

	public HibernateFavorListVisitor(Session session, Class entityClz,
			int start, int size) {
		super(session, entityClz, start, size);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.nanhill.moo.domain.search.favor.FavorVisitor#visitFavorAuthorId(org.nanhill.moo.domain.search.favor.FavorAuthorIdCriterion)
	 */
	public void visitAuthorId(FavorCriterion criterion) throws SearchException {
		try {
			createCriteria("author").add(
					Expression.eq("id", criterion.getValue()));
		} catch (HibernateException e) {
			throw new SearchException(e);
		}
	}

	public void visitCostId(FavorCriterion criterion) throws SearchException {
		try {
			createCriteria("cost").add(
					Expression.eq("id", criterion.getValue()));
		} catch (HibernateException e) {
			throw new SearchException(e);
		}
	}

	public void visitCategoryId(FavorCriterion criterion)
			throws SearchException {
		try {
			createCriteria("category").add(
					Expression.eq("id", criterion.getValue()));
		} catch (HibernateException e) {
			throw new SearchException(e);
		}
	}

	public void visitIdOrder(FavorCriterion criterion) throws SearchException {
		if (SearchConstant.DESC == (Boolean) criterion.getValue())
			addOrder(Order.desc("id"));
		else {
			throw new IllegalStateException(
					"Illegal Favor state: id order must be desc.");
		}
	}

	// @Override
	// protected void buildQuery() throws SearchException {
	// super.buildQuery();
	// if (SearchConstant.DESC == favorIdDesc)
	// criteria.addOrder(Order.desc("id"));
	// }

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.nanhill.commons.pattern.search.SearchVisitor#doSearch(java.util.List)
	 */
	@SuppressWarnings("unchecked")
	protected void doInternalSearch() throws SearchException {
		try {
			favorList = criteria.list();
		} catch (HibernateException e) {
			throw new SearchException(e);
		}
	}

	public List<Favor> getFavorList() {
		return favorList;
	}

}
